package com.heima.article.service.impl;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ApArticleService;
import com.heima.common.constants.ArticleConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.article.dtos.ArticleHomeDto;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.article.vos.HotArticleVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.WmThreadLocalUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ApArticleServiceImpl implements ApArticleService {
    @Autowired
    private ApArticleMapper apArticleMapper;

    @Autowired
    private ApArticleContentMapper apArticleContentMapper;
    @Autowired
    private ApArticleConfigMapper configMapper;
    @Autowired
    private ArticleFreemarkerServiceImpl articleFreemarkerService;
    @Autowired
    private CacheService cacheService;

    /**
     * 根据条件查询文章的列表数据
     *
     * @param dto
     * @param type 1为加载更多  2为加载最新
     * @return
     */
    @Override
    public ResponseResult load(ArticleHomeDto dto, byte type) {
        List<ApArticle> list = apArticleMapper.load(dto, type);

        return ResponseResult.okResult(list);
    }

    /**
     * 加载文章列表
     *
     * @param dto
     * @param type      1 加载更多   2 加载最新
     * @param firstPage true 是首页  false 不是首页
     * @return
     */
    @Override
    public ResponseResult loadArticleListV2(ArticleHomeDto dto, byte type, boolean firstPage) {
        //1. 判断firstPage是否为true 如果为true则冲redis查询数据 否则从数据库查询
        if(firstPage){
            String key = ArticleConstants.HOT_ARTICLE_FIRST_PAGE + dto.getTag();
            String json = cacheService.get(key);
            if(StringUtils.isNotBlank(json)){
                List<HotArticleVo> voList = JSON.parseArray(json, HotArticleVo.class);

                return ResponseResult.okResult(voList);
            }

        }

        return load(dto, type);

    }

    /**
     * 保存APP端文章内容
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult saveArticle(ArticleDto dto) throws Exception {
        //1.检查参数
        if (null == dto) {
            ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //2.判断dto中是否包含文章id，如果存在走修改，如果不存在则走新增
        ApArticle apArticle = new ApArticle();
        BeanUtils.copyProperties(dto, apArticle);
        if (null == dto.getId()) {
            //2.1(否) 新增一个文章--三张表（保存文章、保存文章配置、保存文章内容）
            // apArticle.setAuthorId((long)WmThreadLocalUtil.get().getApUserId());
            apArticleMapper.insert(apArticle);
            ApArticleContent content = new ApArticleContent();
            content.setContent(dto.getContent());
            content.setArticleId(apArticle.getId());


            apArticleContentMapper.insert(content);


            ApArticleConfig config = new ApArticleConfig();
            config.setArticleId(apArticle.getId());
            config.setIsDelete(Boolean.FALSE);
            config.setIsDown(Boolean.FALSE);
            config.setIsForward(Boolean.TRUE);
            config.setIsComment(Boolean.TRUE);
            configMapper.insert(config);

        }else {
            //2.2（是) 修改文章-->两张表（修改文章内容、保存文章内容）
            apArticleMapper.updateById(apArticle);
            ApArticleContent content = apArticleContentMapper.selectOne(Wrappers.<ApArticleContent>lambdaQuery()
                    .eq(ApArticleContent::getArticleId, apArticle.getId()));
            content.setContent(dto.getContent());
            apArticleContentMapper.updateById(content);

            //生成静态页面-使用异步方式来生成
            articleFreemarkerService.buildArticleToMinIO(apArticle.getId());
        }
        //3.封装返回结果
        return ResponseResult.okResult(apArticle.getId());
    }
}
